package com.fenghongzhang.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {

    private Button play;
    private Button pause;
    private Button restart;
    private Button stop;

    //全局要单例
    private MediaPlayer mediaPlayer = new MediaPlayer();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        play = (Button) findViewById(R.id.play);
        pause = (Button) findViewById(R.id.pause);
        restart = (Button) findViewById(R.id.restart);
        stop = (Button) findViewById(R.id.stop);



    }

    public void play(View view) {
        //重置播放器的状态
        mediaPlayer.reset();
        /**
         * 可以是网址,
         * 也是可以本地文件.
         */
        try {
            mediaPlayer.setDataSource("http://mpge.5nd.com/2015/2015-11-26/69708/1.mp3");
            //加载时间过长
//            mediaPlayer.prepare();
            mediaPlayer.prepareAsync();//
            //监听异步加载完成
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    //播放
                    mediaPlayer.start();
                }
            });


        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void pause(View view) {
        //暂停
        mediaPlayer.pause();
    }

    public void restart(View view) {
        mediaPlayer.start();
    }

    public void stop(View view) {
        mediaPlayer.stop();
    }
}
